package com.pearlsoft.webapp.core.dataset.factory.jdbc;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.ResultSetExtractor;

import com.pearlsoft.commons.utils.ClassUtil;
import com.pearlsoft.webapp.core.dataset.DataSetException;
import com.pearlsoft.webapp.core.dataset.QueryHandler;
import com.pearlsoft.webapp.core.dataset.factory.AbstractQueryHandlerFactory;
import com.pearlsoft.webapp.core.dataset.spi.ContextQueryHandler;

/**
 * 
 * JdbcDataSetHandlerFactory
 * 
 * @Creator haitingr
 * @Create-DateTime 2011-10-25
 */
public class JdbcQueryHandlerFactory extends AbstractQueryHandlerFactory {

	protected JdbcTemplate jdbcTemplate;

	public QueryHandler create(final String handlerName) throws DataSetException {
		String type = this.jdbcTemplate.query("select qh_type from judp_query_handler where qh_name=?",
				new PreparedStatementSetter() {
					public void setValues(PreparedStatement ps) throws SQLException {
						ps.setString(1, handlerName);
					}
				}, new ResultSetExtractor<String>() {
					public String extractData(ResultSet rs) throws SQLException, DataAccessException {
						if (rs.next()) {
							return rs.getString(1);
						}
						return null;
					}
				});
		try {
			QueryHandler handler = (QueryHandler) ClassUtil.instance(type);
			if (handler instanceof ContextQueryHandler) {
				((ContextQueryHandler) handler).setApplicationContext(context);
			}
			return handler;
		} catch (Exception e) {
			throw new DataSetException(e);
		}

	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

}
